import cv2
import os
import numpy as np

# 全局变量
drawing = False
ix, iy = -1, -1
rectangles = []  # 存储多个ROI区域 ((x1, y1), (x2, y2))

# 加载图像
image = cv2.imread('images/example.jpg')  # 请修改为你的图片路径
if image is None:
    raise FileNotFoundError("图像未找到，请检查路径。")

clone = image.copy()

# 鼠标回调函数
def select_roi(event, x, y, flags, param):
    global ix, iy, drawing, image, rectangles, clone

    if event == cv2.EVENT_LBUTTONDOWN:
        drawing = True
        ix, iy = x, y

    elif event == cv2.EVENT_MOUSEMOVE and drawing:
        image = clone.copy()
        cv2.rectangle(image, (ix, iy), (x, y), (0, 255, 0), 2)
        cv2.imshow("images", image)

    elif event == cv2.EVENT_LBUTTONUP:
        drawing = False
        x1, y1 = min(ix, x), min(iy, y)
        x2, y2 = max(ix, x), max(iy, y)
        rectangles.append(((x1, y1), (x2, y2)))
        cv2.rectangle(clone, (x1, y1), (x2, y2), (0, 255, 0), 2)
        image = clone.copy()
        cv2.imshow("images", image)

# 设置窗口和回调
cv2.namedWindow("images")
cv2.setMouseCallback("images", select_roi)

print("🔧 提示：请使用鼠标左键在图像上多次框选区域，按任意键结束。")
cv2.imshow("images", image)
cv2.waitKey(0)
cv2.destroyAllWindows()

# 输出坐标
print("\n🟢 你选择的ROI坐标如下：")
for idx, ((x1, y1), (x2, y2)) in enumerate(rectangles, start=1):
    print(f"x{idx}1, y{idx}1 = {x1}, {y1}")
    print(f"x{idx}2, y{idx}2 = {x2}, {y2}")


# ========== 2. 处理文件夹内的图像 ==========
# input_dir = 'images'  # 所有图像所在的文件夹
output_dir = 'firstoutput'  # 输出结果保存位置
os.makedirs(output_dir, exist_ok=True)


# 画所有ROI
for i, ((x1, y1), (x2, y2)) in enumerate(rectangles, start=1):
    cv2.rectangle(image, (x1, y1), (x2, y2), (0, 0, 255), 2)
    cv2.putText(image, f'ROI{i}', (x1, y1 - 8), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 1)

# 保存结果
save_path = os.path.join(output_dir, 'output.jpg')
cv2.imwrite(save_path, image)

print("\n🎉 图像标注完成，已保存到 firstoutput/ 文件夹中。")

# ========== 3. 处理单张图像，将ROI区域涂黑 ==========

# 创建输出文件夹
output_dir_black = 'thirdoutput'
os.makedirs(output_dir_black, exist_ok=True)

# 读取原始图像
original_image = cv2.imread('images/example.jpg')  # 请确保路径与最开始一致
if original_image is None:
    print("⚠️  无法读取原始图像，无法进行涂黑处理。")
else:
    # 创建一个全黑的遮罩图像，尺寸与原图相同
    mask = np.zeros_like(original_image)

    # 在遮罩上，将所有ROI区域设置为白色（保留区域）
    for (x1, y1), (x2, y2) in rectangles:
        cv2.rectangle(mask, (x1, y1), (x2, y2), (255, 255, 255), -1)

    # 使用遮罩，只保留ROI区域，其余部分变为黑色
    result_image = cv2.bitwise_and(original_image, mask)

    # 保存结果
    save_path_black = os.path.join(output_dir_black, 'blacked_output.jpg')
    cv2.imwrite(save_path_black, result_image)

    print(f"\n✅ ROI之外的区域已被涂黑，只保留框选区域，结果已保存至 '{save_path_black}'。")